package org.yinxue.swing.core.panel;

import org.yinxue.swing.core.domain.FileObject;

import javax.swing.*;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.*;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.io.File;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.stream.Collectors;

public class YxTree extends JScrollPane {

    public JTree jTree = new JTree();
    public String filePath;

    public YxTree() {
        super(VERTICAL_SCROLLBAR_ALWAYS, HORIZONTAL_SCROLLBAR_AS_NEEDED);
        setViewportView(jTree);
        getVerticalScrollBar().setUnitIncrement(20);
//        final Font currentFont = jTree.getFont();
//        final Font bigFont = new Font(currentFont.getName(), currentFont.getStyle(), currentFont.getSize() + 10);
//        jTree.setFont(bigFont);
        // todo 实现jtree 自定义icon https://blog.csdn.net/qq_40834643/article/details/126365489
        jTree.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        jTree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
        // 解决字体被遮蔽的问题
        jTree.setRowHeight(18);
        this.setTransferHandler(new TransferHandler() {

            @Override
            public boolean importData(JComponent comp, Transferable t) {
                try {
                    Object o = t.getTransferData(DataFlavor.javaFileListFlavor);

                    String filepath = o.toString();
                    if (filepath.startsWith("[")) {
                        filepath = filepath.substring(1);
                    }
                    if (filepath.endsWith("]")) {
                        filepath = filepath.substring(0, filepath.length() - 1);
                    }
                    System.out.println(filepath);
                    refreshTree(filepath);
                    return true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return false;
            }

            @Override
            public boolean canImport(JComponent comp, DataFlavor[] flavors) {
                for (int i = 0; i < flavors.length; i++) {
                    if (DataFlavor.javaFileListFlavor.equals(flavors[i])) {
                        return true;
                    }
                }
                return false;
            }
        });
    }

    public void addTreeSelectionListener(TreeSelectionListener l) {
        jTree.addTreeSelectionListener(l);
    }

    public Object getLastSelectedPathComponent() {
        return jTree.getLastSelectedPathComponent();
    }

    // TODO 获取列表
    public List<Object> getSelectObjects() {
        TreePath[] treePaths = jTree.getSelectionPaths();
        if (treePaths == null || treePaths.length == 0) {
            return Collections.emptyList();
        }
        return Arrays.stream(treePaths).map(path -> ((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject()).collect(Collectors.toList());
    }

    public void setRoot(MutableTreeNode root) {
        jTree.removeAll();
        ((DefaultTreeModel) jTree.getModel()).setRoot(root);
    }

    public void refreshTree(String dirPath) {
        filePath = dirPath;
        DefaultMutableTreeNode root = createTreeNode(new FileObject(filePath, new File(filePath)));
        buildTree(root, filePath);
        this.setRoot(root);
    }

    public void buildTree(DefaultMutableTreeNode root, String path) {
        File rootFile = new File(path);
        File[] childFiles = rootFile.listFiles();
        if (childFiles == null) {
            return;
        }
        for (File childFile : childFiles) {
            // 对象需要调整为
            DefaultMutableTreeNode child = createTreeNode(new FileObject(childFile.getName(), childFile));
            root.add(child);
            if (childFile.isDirectory()) {
                buildTree(child, childFile.getPath());
                if (childFile.listFiles() == null || childFile.listFiles().length == 0) {
                    child.add(createTreeNode(new FileObject("空", null)));
                }
            }
        }
    }

    public DefaultMutableTreeNode createTreeNode(Object userObject) {
        return new DefaultMutableTreeNode(userObject);
    }


    // TODO 节点展开 https://www.cnblogs.com/Helloxxm/articles/8973087.html  优化为渲染树节点时
    public void expand(FileObject fileObject) {
        TreeNode root = (TreeNode) jTree.getModel().getRoot();
        expandTree(jTree, new TreePath(root), fileObject);
    }


    private void expandTree(JTree tree, TreePath parent, FileObject fileObject) {
        TreeNode node = (TreeNode) parent.getLastPathComponent();
        if (node.getChildCount() >= 0) {
            for (Enumeration<?> e = node.children(); e.hasMoreElements(); ) {
                DefaultMutableTreeNode n = (DefaultMutableTreeNode) e.nextElement();
                FileObject findObject = (FileObject) n.getUserObject();
                TreePath path = parent.pathByAddingChild(n);
                if (n.isLeaf()) {
                    continue;
                }
                if (findObject.file.getAbsolutePath().equals(fileObject.file.getAbsolutePath())) {
                    tree.expandPath(path);
                    // 需要返回跳出循环
                    return;
                } else {
                    expandTree(tree, path, fileObject);
                }
            }
        }
    }
}
